<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2017/12/26
 * Time: 下午2:20
 */
class Order_model extends CI_Model
{

    public function __construct(){
        $this->load->database();
        $this->load->helper("common");
    }

    // 根据箱子ID 查询使用中的订单
    public function query_order_by_box_id($box_id){
        $sql = "select * from app_order WHERE status = 1 AND box_id = ".$box_id;
        $order_info = $this->db->query($sql)->row_array();

        return $order_info;
    }

    // 查询订单详情
    public function query_order_info($id)
    {
        $sql = "SELECT
  ao.*,
  (SELECT aw.nick_name
   FROM app_wechat aw INNER JOIN app_user au ON aw.id = au.wechat_id
   WHERE au.id = ao.user_id)            AS sender_nick_name,
  (SELECT aw.nick_name
   FROM app_wechat aw LEFT JOIN app_user AS au on aw.id = au.wechat_id
   WHERE au.id = ao.receiver_user_id) AS receiver_nick_name
FROM app_order ao WHERE ao.id = $id;";
        $order_info = $this->db->query($sql)->row_array();

        return $order_info;
    }

    // 进行中的订单数量
    public function count_going_orders($uid)
    {
        $sql = "select count(1) as total from app_order WHERE status in (1,2) AND is_paid = 0 AND user_id = $uid OR (receiver_user_id = $uid AND status IN (1, 2) AND is_paid = 0)";
        $order_info = $this->db->query($sql)->row_array();
        $res = 0;
        if($order_info)
        {
            $res = $order_info['total'];
        }
        return $res;
    }

    // 根据条件查询 订单
    public function query_sending_order($status_arr,$user_id,$receiver_user_id,$box_id,$page=1,$psize=10,$type = 1){
        $sql = "SELECT
  ao.*,
  (SELECT aw.nick_name
   FROM app_wechat aw INNER JOIN app_user au ON aw.id = au.wechat_id
   WHERE au.id = ao.user_id)            AS sender_nick_name,
  (SELECT aw.nick_name
   FROM app_wechat aw LEFT JOIN app_user AS au on aw.id = au.wechat_id
   WHERE au.id = ao.receiver_user_id) AS receiver_nick_name
FROM app_order ao WHERE 1 = 1 ";
        if($status_arr){
            $sq = implode(',',$status_arr);
            $sql .= " and status in ($sq)";
        }
        if($type == 1)
        {
            // 进行中的订单
            $sql .= " and is_paid = 0";
        }else{
            // 历史订单
            $sql .= " and status = 0 OR (status = 2 AND is_paid = 1)";
        }
        if($user_id){
            $sql .= " and (user_id = ".$user_id;
            if($receiver_user_id){
                $sql .= " or receiver_user_id = ".$receiver_user_id;
            }
            $sql .= ")";
        }
        if($box_id){
            $sql .= " and box_id = ".$box_id;
        }
        // 排序
        $sql .= " order by id desc";

        // 分页
        $page = isset($page)?(int)$page:1;
        $psize = isset($psize)?(int)$psize:10;
        $limit_from = ($page-1)*$psize;
        $sql.=" limit ".$limit_from.",".$psize;

        $order_list = $this->db->query($sql)->result_array();

        return $order_list;
    }

    // 生成订单价格
    public function deal_order_money($box_id,$order_id){
        $order_info = $this->order_model->query_order_info($order_id);
        $sql = "select a.price from app_box_type a LEFT JOIN app_box b ON a.id = b.type_id WHERE b.id = ".$box_id;
        $keyinfo = $this->db->query($sql)->row_array();
        if(!$keyinfo)
        {
            send_json(array('code'=>-1,'data'=>'','msg'=>"每日费用未设置"));
        }
        $rate = $keyinfo['price'];
        $days = diffBetweenTwoDays($order_info['end_time'],$order_info['start_time']);
        $money = number_format($rate*$days,2);
        $bool = $this->db->where(array("id"=>$order_id))->update('app_order',array("fee"=>$money));
        return $bool;
    }

    // 查询物流信息
    public function order_logistics($tracking_number)
    {
        //发送数据
        $url = "http://www.kuaidi100.com/autonumber/auto?num=".$tracking_number."&key=".$this->config->item("logistics_key");
        $company_data = curl_request($url);
        $company_data = json_decode($company_data,true);
        if($company_data && isset($company_data[0]['comCode'])){
            $company = $company_data[0]['comCode'];
            $post_data = array();
            $post_data["customer"] = $this->config->item("logistics_customer");;
            $key= $this->config->item("logistics_key") ;
            $push = array("com"=>$company,"num"=>$tracking_number);
            $post_data["param"] = json_encode($push);

            $url='http://poll.kuaidi100.com/poll/query.do';
            $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
            $post_data["sign"] = strtoupper($post_data["sign"]);
            $o="";
            foreach ($post_data as $k=>$v)
            {
                $o.= "$k=".($v)."&";		//默认UTF-8编码格式
            }
            $post_data=substr($o,0,-1);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $result = curl_exec($ch);
            $data = str_replace("\"",'"',$result );
            $data = json_decode($data,true);
            if($data['message'] == 'ok'){
                $com_code = $data['com'];
                $data['com_name'] = isset($this->config->item('logistics_key_value')[$com_code]) ? $this->config->item('logistics_key_value')[$com_code] : '';
                return $data;
            }else{
                return '';
            }
        }else{
            return '';
        }
    }


}